library(tidyverse)

get_all_eol_data <- function(con){
    # returns main query for all data
    fir <- get_fir_table(con)
    dyn <- get_dyn_table(con)
    union(fir, dyn)
}


get_revision_cancer_monthly_data <- function(con) {
    # returns query for monthly subset of revision cancer table
    (get_revision_cancer_data(con)
     %>% filter(S_sample_source_XX %in% c('cnr_data','cnr_data2','cnr_data3','cnr_data4',
                                          'cnr_data5','cnr_data6','cnr_data7', 'cnr_data8',
                                          'cnr_data9','cnr_data10','cnr_data11','cnr_data12'))
    )
}


get_eol_table_names <-  function() {
    # returns list with table names
    list(
        main      = "FeaturesExtraction"
        , ids     = "tempTable_sampleIDs"
        , table_3 = "FeaturesExtraction_3rdTable"
        , table_4 = "FeaturesExtraction_4thTable"
        , revision_cancer = "FeaturesExtraction2"
        , cancer_events   = "FeaturesExtraction_events"
        , cancer_events_full   = "FeaturesExtraction_events_2"
    )
}

get_variables_list <- function() {
    # returns vars object with relevant colnames for queries
    vars(
        -contains("unit"), -contains("pDX"), -contains("date"),
        c('S_index_date_XX','index_date_month', 'index_date_year', 'DMG_date_of_death_XX'),
        - c("ADMS_LSTADM_zihuiIshpuzBik_XX", "ADMS_lead_zihuiIshpuzBik_XX")
    )
}

get_main_table <- function(con) {
    # create sql query to main table with only relevant columns
    (get_eol_table_names()$main
     %>% get_z_table(con, .)
     %>% select_at(get_variables_list())
    )
}

get_fir_table <- function(con) {
    # create sql query to fixed data
    (get_main_table(con)
     %>% filter(S_sample_source_XX %in% c("all_data", "cnr_data"))
    )
}

get_dyn_table <- function(con){
    # create sql query to dynamic cancer data
    (get_main_table(con)
     %>% filter(S_sample_source_XX %in% c('cnr_data2','cnr_data3','cnr_data4','cnr_data5','cnr_data6','cnr_data7',
                                          'cnr_data8','cnr_data9','cnr_data10','cnr_data11','cnr_data12'),
                (is.null(DMG_date_of_death_XX) | DATEDIFF(DAY, S_index_date_XX ,DMG_date_of_death_XX )  >= 0))
    )
}

get_table_3 <- function(con, sample_name) {
    # create sql query to table 3
    eol_names <- get_eol_table_names()
    table_3 <- get_z_table(con, eol_names$table_3)
    ids <- get_z_table(con, eol_names$ids)
    (table_3
        %>% mutate(temp_date = DATEFROMPARTS(S_index_date_XX_year, S_index_date_XX_month, S_index_date_XX_day))
        %>% inner_join(ids, c("id_var" = "id_var", "temp_date" = "index_date"))
        %>% filter(sample_source %in% sample_name)
        %>% select_at(vars(colnames(table_3)))
    )
}

get_monthly_costs <- function(con) {
    # query month;y costs
    get_z_table(con, "FeaturesExtraction_2year_monthly_costs_cnr")
}


get_UTL_table_names <-  function(con,period) {
  # returns list with table names
  paste0("tempTable_cost_",period,"d_before_cancer_events_test"  )
}

join_utl_slice <- function(.data,period = 180) {
  .data %>% 
    left_join( get_UTL_table(con, period = period) ,
               by = c("id_var" = "id_var",
                      "S_index_date_XX" = "index_date")
    )
}

add_UTL_features <- function(.data) {
  .data %>% 
    join_utl_slice(180)  %>% 
    join_utl_slice(90)   %>% 
    join_utl_slice(60)   %>% 
    join_utl_slice(30)            
}

get_phat0 <- function(path =  "path_name/",        
                      file_name = "revision_monthly_cnr_data.RData") {
  
  data_name <- load(file=paste0(path,file_name))
  data <- get(data_name)
  
  data$preds_test %>% 
    select("id_var","preds_after_bayes") %>% 
    dplyr::rename(EVE_phat0 = preds_after_bayes)
}


join_phat0 <- function(.data, file_name = "revision_monthly_cnr_data.RData") {
  .data %>% 
    left_join( get_phat0(file_name = file_name ) ,
               by = c("id_var" = "id_var"))
}

gen_intensity <- function(.data, intensity_wards = c("oncology","internal_medicine",
                                                     "geriatry","rehabilitation"),
                          category_var ,profession_var, new_varname ) {
  .data %>%
    mutate({{new_varname}} := case_when({{category_var}} %in% c("elective","urgent") &
                                          {{profession_var}} %in% intensity_wards ~ "Low",
                                        {{category_var}} %in% c("elective","urgent") &
                                          !{{profession_var}} %in% intensity_wards ~ "High",
                                        !{{category_var}} %in% c("elective","urgent") ~ {{category_var}}))
}


do_intensity<- function(.data) {
  .data %>% 
    gen_intensity(category_var = EVE_category, profession_var = EVE_profession, new_varname = EVE_intensity) %>% 
    gen_intensity(category_var = EVE_lag1_category, profession_var = EVE_lag1_profession, new_varname = EVE_lag1_intensity) %>% 
    gen_intensity(category_var = EVE_lag2_category, profession_var = EVE_lag2_profession, new_varname = EVE_lag2_intensity) %>% 
    gen_intensity(category_var = EVE_lag3_category, profession_var = EVE_lag3_profession, new_varname = EVE_lag3_intensity) %>% 
    gen_intensity(category_var = EVE_lag4_category, profession_var = EVE_lag4_profession, new_varname = EVE_lag4_intensity) %>% 
    gen_intensity(category_var = EVE_lag5_category, profession_var = EVE_lag5_profession, new_varname = EVE_lag5_intensity) %>% 
    gen_intensity(category_var = EVE_lag6_category, profession_var = EVE_lag6_profession, new_varname = EVE_lag6_intensity) %>% 
    gen_intensity(category_var = EVE_lag7_category, profession_var = EVE_lag7_profession, new_varname = EVE_lag7_intensity) 
}

